﻿using OfficeOpenXml;
using ResilienceCompute.Tool;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using LicenseContext = OfficeOpenXml.LicenseContext;

namespace ResilienceCompute
{
    public partial class MainForm : Form
    {
        public static double NumA { get; set; }
        public static double NumB { get; set; }
        private List<double> readFileDataList = new List<double>();

        public MainForm()
        {
            InitializeComponent();
            this.Load += MainForm_Load;
            this.FormClosing += MainForm_FormClosing;
            this.btn_handStart.Click += Btn_handStart_Click;
            this.btn_openFile.Click += Btn_openFile_Click;
            this.btn_handStop.Click += Btn_handStop_Click;
            chart.ChartAreas[0].AxisX.Title = "数量";
            chart.ChartAreas[0].AxisY.Title = "压力";
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            SiemenPlc siemen = new SiemenPlc("192.168.110.10", "DB7300", 0);
            siemen.DataCallback += (value) =>
            {
                this.BeginInvoke(new Action(() =>
                {
                    lbl_resilienceA.Text = value.Item1.ToString();
                    chart.Series[0].Points.Clear();
                    foreach (var item in value.Item2)
                    {
                        chart.Series[0].Points
                        .Add(item);
                    }
                }));
            };
            siemen.Start();
            SiemenPlc siemenPlc = new SiemenPlc("192.168.110.10", "DB9300", 1);
            siemenPlc.DataCallback += (value) =>
            {
                this.BeginInvoke(new Action(() =>
                {
                    lbl_resilienceB.Text = value.Item1.ToString();
                    chart.Series[1].Points.Clear();
                    foreach (var item in value.Item2)
                    {
                        chart.Series[1].Points
                        .Add(item);
                    }
                }));
            };
            siemenPlc.Start();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            var result = MessageBox.Show("是否退出当程序？", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
            if (result != DialogResult.OK)
            {
                e.Cancel = true;
            }
        }

        private void Btn_openFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = "D:\\YULAYAFILE";
            openFileDialog.FilterIndex = 2;
            openFileDialog.RestoreDirectory = true;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                readFileDataList.Clear();
                chart.Series[0].Points.Clear();
                // 获取选定文件的路径
                string filePath = openFileDialog.FileName;
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                try
                {
                    using (ExcelPackage package = new ExcelPackage(new FileInfo(filePath)))
                    {
                        ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
                        int rowCount = worksheet.Dimension.Rows;
                        int colCount = worksheet.Dimension.Columns;
                        for (int row = 2; row <= rowCount; row++)
                        {
                            for (int col = 1; col <= colCount; col++)
                            {
                                double value = Convert.ToDouble(worksheet.Cells[row, col].Value);
                                //chart.Series[0].Points.Add(value);
                                readFileDataList.Add(value);
                            }
                        }
                    }
                }
                catch
                {
                    MessageBox.Show("打开文件错误", "警告");
                }
            }
        }

        private ContinuousPressureReader reader;

        private void Btn_handStart_Click(object sender, EventArgs e)
        {
            const double excitationVoltage = 5.0;      // 激励电压10V
            const double sensitivity = 1.5725;        // 1.5725 mV/V
            const double fullScaleLoad = 9807.1;       // 9.8071 kN = 9807.1 N
            this.btn_handStart.Enabled = false;
            reader = new ContinuousPressureReader(
            deviceName: "cDAQ1Mod1",
            0,
            excitationVoltage: excitationVoltage,
            sensitivity: sensitivity,
            fullScaleLoad: fullScaleLoad,
            samplingRate: 1024,
            bufferSize: 1000);

            // 订阅数据处理完成事件
            reader.OnDataProcessingComplete += (forceData) =>
            {
                Console.WriteLine($"处理完成，共 {forceData.Length} 个数据点");
                chart.Series[1].Points.Clear();
                foreach (var item in forceData)
                {
                    chart.Series[1].Points
                    .Add(item);
                }
            };

            // 执行零点校准（必须在无负载状态下）
            Console.WriteLine("开始零点校准（确保无负载状态）...");
            reader.PerformZeroCalibration();
            // 开始连续采集
            Console.WriteLine("开始连续采集...");
            reader.Start();
        }

        private void Btn_handStop_Click(object sender, EventArgs e)
        {
            this.btn_handStart.Enabled = true;
            reader.Stop();
        }
    }
}